package com.xinlong.shop.core.blind.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xinlong.shop.core.blind.entity.BlindBoxGoods;
import com.xinlong.shop.core.blind.mapper.BlindBoxGoodsMapper;
import com.xinlong.shop.core.blind.service.IBlindBoxGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import java.util.List;

/**
 * <p>
 * 盲盒关联商品表 服务实现类
 * </p>
 *
 * @author Sylow
 * @since 2023-05-15
 */
@Service
public class BlindBoxGoodsServiceImpl extends ServiceImpl<BlindBoxGoodsMapper, BlindBoxGoods> implements IBlindBoxGoodsService {

    @Override
    public void update(BlindBoxGoods blindBoxGoods, Integer id) {
        UpdateWrapper<BlindBoxGoods> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        this.update(blindBoxGoods, updateWrapper);
    }
    @Override
    public void delete(Integer id) {
        UpdateWrapper<BlindBoxGoods> deleteWrapper = new UpdateWrapper<>();
        deleteWrapper.eq("id", id);
        this.remove(deleteWrapper);
    }

    @Override
    public boolean batchSaveBlindBoxGoods(List<BlindBoxGoods> blindBoxGoodsList, Integer blindBoxId) {
        Long nowTime = DateUtil.currentSeconds();
        blindBoxGoodsList.forEach(blindBoxGoods -> {
            blindBoxGoods.setBlindBoxId(blindBoxId);
            blindBoxGoods.setCreateTime(nowTime);
        });
        boolean result = this.saveBatch(blindBoxGoodsList);
        return result;
    }

    @Override
    public List<BlindBoxGoods> findByBlindBoxId(Integer blindBoxId) {
        QueryWrapper<BlindBoxGoods> query = new QueryWrapper<>();
        query.eq("blind_box_id", blindBoxId);
        List<BlindBoxGoods> blindBoxGoodsList = this.list(query);
        return blindBoxGoodsList;
    }

    @Override
    public boolean deleteByBlindBoxId(Integer blindBoxId) {
        QueryWrapper<BlindBoxGoods> query = new QueryWrapper<>();
        query.eq("blind_box_id", blindBoxId);
        boolean result = this.remove(query);
        return result;
    }

    @Override
    public List<BlindBoxGoods> findByBlindBoxIdAndTag(Integer blindBoxId, String tag) {
        QueryWrapper<BlindBoxGoods> query = new QueryWrapper<>();
        query.eq("blind_box_id", blindBoxId);
        query.eq("tag", tag);
        return this.list(query);
    }

    @Override
    public boolean reduceStock(Integer blindBoxId, Integer goodsId, Integer stock) {
        UpdateWrapper<BlindBoxGoods> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("blind_box_id", blindBoxId);
        updateWrapper.eq("goods_id", goodsId);
        updateWrapper.setSql("stock = stock - " + stock);
        return this.update(updateWrapper);
    }

}
